package com.woniu.gf.pawn.management.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniu.gf.pawn.comm.core.domain.Management;
import com.woniu.gf.pawn.comm.core.dto.ResultDto;
import com.woniu.gf.pawn.comm.core.exception.PawnAuthenException;
import com.woniu.gf.pawn.comm.core.exception.PawnExceptionCode;
import com.woniu.gf.pawn.comm.core.util.JwtUtil;
import com.woniu.gf.pawn.management.dto.ManagementDto;
import com.woniu.gf.pawn.management.dto.ManagementInfoDto;
import com.woniu.gf.pawn.management.param.*;
import com.woniu.gf.pawn.management.service.ManagementService;
import com.woniu.gf.pawn.management.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2020-10-13
 */
@RestController
@RequestMapping("/management")
@Slf4j
@Api(tags = "管理员")
@CrossOrigin
public class ManagementController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private ManagementService managementService;
    @Autowired
    private PermissionService permissionService;

    /**
    *@Description: 用户名密码登陆
    *@return:
    */
    @PostMapping("/passwordLogin")
    @ApiOperation("用户名密码登陆")
    public ResultDto passwordLogin(@RequestBody @Valid ManagementPasswordLoginParam managementPasswordLoginParam){
        log.info("{}:尝试登陆", managementPasswordLoginParam.getManagementName());
        Management management = new Management();
        BeanUtils.copyProperties(managementPasswordLoginParam,management);
        QueryWrapper<Management> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("management_name",management.getManagementName());
        queryWrapper.eq("management_password",management.getManagementPassword());
        queryWrapper.eq("management_status","正常");
        Management managementOne = managementService.getOne(queryWrapper);
        if(managementOne==null){
            log.error("{}:登陆失败，原因：{}", managementPasswordLoginParam.getManagementName(),PawnExceptionCode.USER_AUTHE_ERROR.getMsg());
            return ResultDto.fail(PawnExceptionCode.USER_AUTHE_ERROR.getCode(),PawnExceptionCode.USER_AUTHE_ERROR.getMsg());
        }
        //查询自己所有权限
        return getResultDto(managementOne);
    }

    /**
    *@Description: 获取短信验证码
    *@return:
    */
    @ApiOperation("获取短信验证码")
    @GetMapping("/getSmsCode/{phone}")
    public ResultDto getSmsCode(@PathVariable("phone") String phone){
        System.out.println(phone);
        Message<String> message= MessageBuilder.withPayload(phone)
                .setHeader("KEYS", UUID.randomUUID().toString().replace("-",""))
                .build();
        rocketMQTemplate.asyncSend("smsCode:phone", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送失败");
            }
        });
        return ResultDto.success(200,"获取成功");
    }

    /**
    *@Description: 短信验证码登陆
    *@return:
    */
    @PostMapping("/smsLogin")
    @ApiOperation("短信验证码登陆")
    public ResultDto smsLogin(@RequestBody @Valid ManagementSmsLoginParam managementSmsLoginParam){
        String code = (String) redisTemplate.opsForValue().get(managementSmsLoginParam.getManagementPhone());
        if(code==null){
            log.error("{}:登陆失败，原因：{}", managementSmsLoginParam.getManagementPhone(),PawnExceptionCode.USER_SMSCODE_ERROR.getMsg());
            return ResultDto.fail(PawnExceptionCode.USER_SMSCODE_ERROR.getCode(),PawnExceptionCode.USER_SMSCODE_ERROR.getMsg());
        }
        if(!managementSmsLoginParam.getCode().equals(code)){
            log.error("{}:登陆失败，原因：{}", managementSmsLoginParam.getManagementPhone(),PawnExceptionCode.USER_SMSCODE_ERROR.getMsg());
            return ResultDto.fail(PawnExceptionCode.USER_SMSCODE_ERROR.getCode(),PawnExceptionCode.USER_SMSCODE_ERROR.getMsg());
        }else {
            Management management = new Management();
            BeanUtils.copyProperties(managementSmsLoginParam,management);
            QueryWrapper<Management> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("management_phone",management.getManagementPhone());
            queryWrapper.eq("management_status","正常");
            Management managementOne = managementService.getOne(queryWrapper);
            if(managementOne==null){
                log.error("{}:登陆失败，原因：{}", managementSmsLoginParam.getManagementPhone(),PawnExceptionCode.USER_PHONE_NONENTITY.getMsg());
               return ResultDto.fail(PawnExceptionCode.USER_PHONE_NONENTITY.getCode(),PawnExceptionCode.USER_PHONE_NONENTITY.getMsg());
            }
            //查询自己所有权限
            return getResultDto(managementOne);
        }
    }
    /**
    *@Description: 数据转换
    *@return:
    */
    private ResultDto getResultDto(Management managementOne) {
        List<String> permissionList = permissionService.selectByManagementId(managementOne.getManagementId());
        System.out.println(permissionList);
        Map<String, Object> map=new HashMap<>();
        map.put("managementId",managementOne.getManagementId());
        map.put("managementName",managementOne.getManagementName());
        map.put("managementPhone",managementOne.getManagementPhone());
        map.put("permissions",permissionList);
        String token = JwtUtil.createToken(map, 24 * 60 * 60);
        Map<String, Object> map1 = JwtUtil.parseToken(token);
        System.out.println(map1.get("permissions")+"--------");
        ManagementDto managementDto = new ManagementDto();
        BeanUtils.copyProperties(managementOne,managementDto);
        managementDto.setToken(token);
        return ResultDto.success(200,"登陆成功",managementDto);
    }

    /**
    *@Description:  新增管理员
    *@return:
    */
    @PostMapping("/addManagement")
    @ApiOperation("新增管理员")
    public ResultDto addManagement(@RequestBody @Valid AddManagementParam addManagementParam){
        Management management = new Management();
        BeanUtils.copyProperties(addManagementParam,management);
        Management managementName=null;
        Management managementPhone=null;
        Management managementNameAndPhone=null;
        QueryWrapper<Management> queryWrapper=new QueryWrapper<>();
        QueryWrapper<Management> queryWrapper2=new QueryWrapper<>();
        if(management.getManagementPhone()==null){
            queryWrapper.eq("management_name",management.getManagementName());
            managementName = managementService.getOne(queryWrapper);
        }else {
            queryWrapper.eq("management_phone",management.getManagementPhone());
            managementPhone = managementService.getOne(queryWrapper);
            queryWrapper2.eq("management_name",management.getManagementName());
            managementNameAndPhone=managementService.getOne(queryWrapper2);
        }
        if(managementName!=null){
            return ResultDto.fail(PawnExceptionCode.USER_ADD_NAME_EXIST.getCode(),PawnExceptionCode.USER_ADD_NAME_EXIST.getMsg());
        }
        if(managementPhone !=null){
            return ResultDto.fail(PawnExceptionCode.USER_ADD_PHONE_EXIST.getCode(),PawnExceptionCode.USER_ADD_PHONE_EXIST.getMsg());
        }
        if(managementNameAndPhone !=null){
            return ResultDto.fail(PawnExceptionCode.USER_ADD_NAME_EXIST.getCode(),PawnExceptionCode.USER_ADD_NAME_EXIST.getMsg());
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(new Date());
        Date dateTime=null;
        try {
            dateTime = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        management.setManagementAddTime(dateTime);
        management.setManagementPassword("123456");
        management.setManagementStatus("正常");
        managementService.save(management);
        return ResultDto.success(200,"新增成功");
    }

    /**
    *@Description: 分页查询所有管理员
    *@return:
    */
    @GetMapping("/selectAllManagement")
    @ApiOperation("分页查询所有管理员")
    public ResultDto selectPageManagement(@Valid SelectManagementParam selectManagementParam){
        System.out.println(selectManagementParam);
        IPage<Management> managementIPage= managementService.selectPageManagement(selectManagementParam);
        return ResultDto.success(200,"查询成功",managementIPage);
    }
    /**
    *@Description: 修改用户状态
    *@return:
    */
    @PutMapping("/alterManagementStatus")
    @ApiOperation("修改用户状态")
    public ResultDto alterManagementStatus(@RequestBody @Valid AlterManagementStatusParam alterManagementStatusParam){
        if(alterManagementStatusParam.getManagementId()<=1){
            return ResultDto.fail(PawnExceptionCode.USER_ADMIN_BAN_ERROR.getCode(),PawnExceptionCode.USER_ADMIN_BAN_ERROR.getMsg());
        }
        Management management = new Management();
        BeanUtils.copyProperties(alterManagementStatusParam,management);
        UpdateWrapper<Management> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("management_id",management.getManagementId());
        updateWrapper.set("management_status",management.getManagementStatus());
        managementService.update(updateWrapper);
        return ResultDto.success(200,"修改成功");
    }

    @GetMapping("selectManagementById")
    @ApiOperation("根据管理员编号查询管理员信息")
    public Management selectManagementById(int managementId){
        Management management = managementService.getById(managementId);
        return management;
    }

    @GetMapping("selectManagementInfo")
    public ResultDto selectManagementInfo(HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Management management = new Management();
        ManagementInfoDto managementInfoDto = new ManagementInfoDto();
        try {
            Map<String, Object> map = JwtUtil.parseToken(token);
            int managementId=(int)map.get("managementId");
            String managementName=(String)map.get("managementName");
            String managementPhone=(String)map.get("managementPhone");
            management.setManagementId(managementId);
            management.setManagementName(managementName);
            management.setManagementPhone(managementPhone);
            BeanUtils.copyProperties(management,managementInfoDto);
        }catch (Exception e){
            throw new PawnAuthenException(PawnExceptionCode.USER_AUTHE_TOKEN_PARSE);
        }
        return ResultDto.success(200,"查询个人信息成功",managementInfoDto);
    }

    /**
    *@Description: 修改管理员密码
    *@return:
    */
    @PutMapping("/alterManagementPassword")
    @ApiOperation("修改管理员密码")
    public ResultDto alterManagementPassword(@RequestBody @Valid AlterManagementPasswordParam alterManagementPasswordParam, HttpServletRequest request){
        String managementOldPassword = alterManagementPasswordParam.getManagementOldPassword();
        String reManagementNewPassword = alterManagementPasswordParam.getReManagementNewPassword();
        String managementNewPassword = alterManagementPasswordParam.getManagementNewPassword();
        String token=request.getHeader("token");
        Map<String, Object> map = JwtUtil.parseToken(token);
        int managementId=(int)map.get("managementId");
        QueryWrapper<Management> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("management_id",managementId);
        queryWrapper.eq("management_password",managementOldPassword);
        int count = managementService.count(queryWrapper);
        if(count==0){
            return ResultDto.fail(PawnExceptionCode.USER_OLD_PASSWORD_ERROR.getCode(),PawnExceptionCode.USER_OLD_PASSWORD_ERROR.getMsg());
        }
        if(!reManagementNewPassword.equals(managementNewPassword)){
            return ResultDto.fail(PawnExceptionCode.USER_TWICE_PASSWORD_ERROR.getCode(),PawnExceptionCode.USER_TWICE_PASSWORD_ERROR.getMsg());
        }
        if(managementNewPassword.equals(managementOldPassword)){
            return ResultDto.fail(PawnExceptionCode.USER_OLD_AND_NEW_PASSWORD_EQUAL_ERROR.getCode(),PawnExceptionCode.USER_OLD_AND_NEW_PASSWORD_EQUAL_ERROR.getMsg());
        }
        UpdateWrapper<Management> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("management_id",managementId);
        updateWrapper.set("management_password",managementNewPassword);
        managementService.update(updateWrapper);
        return ResultDto.success(200,"修改密码成功");
    }

    /**
    *@Description: 修改管理员信息
    *@return:
    */
    @PutMapping("/alterManagementInfo")
    @ApiOperation("修改管理员信息")
    public ResultDto alterManagementInfo(@RequestBody @Valid AlterManagementInfoParam alterManagementInfoParam,HttpServletRequest request){
        String token=request.getHeader("token");
        Map<String, Object> map = JwtUtil.parseToken(token);
        int managementId=(int)map.get("managementId");
        Management management = managementService.getById(managementId);
        String managementName = alterManagementInfoParam.getManagementName();
        String managementPhone = alterManagementInfoParam.getManagementPhone();
        QueryWrapper<Management> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("management_name",managementName);
        Management managementByName = managementService.getOne(queryWrapper);
        QueryWrapper<Management> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("management_phone",managementPhone);
        Management managementByPhone = managementService.getOne(queryWrapper1);
        if(managementByName !=null){
            if(!managementByName.getManagementName().equals(management.getManagementName())){
                return ResultDto.fail(PawnExceptionCode.USER_ADD_NAME_EXIST.getCode(),PawnExceptionCode.USER_ADD_NAME_EXIST.getMsg());
            }
        }
        if(managementByPhone !=null){
            if(!managementByPhone.getManagementPhone().equals(management.getManagementPhone())){
                return ResultDto.fail(PawnExceptionCode.USER_ADD_PHONE_EXIST.getCode(),PawnExceptionCode.USER_ADD_PHONE_EXIST.getMsg());
            }
        }
        UpdateWrapper<Management> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("management_id",managementId);
        updateWrapper.set("management_name",managementName);
        updateWrapper.set("management_phone",managementPhone);
        managementService.update(updateWrapper);
        return ResultDto.success(200,"修改用户信息成功");
    }

    /**
    *@Description: 登出
    *@return:
    */
    @GetMapping("/logout")
    @ApiOperation("管理员登出")
    public ResultDto logout(){
        return ResultDto.success(200,"登出成功");
    }
}

